package co.yixiang.yshop.module.crm.service.crmanalysis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import co.yixiang.yshop.framework.common.enums.CommonStatusEnum;
import co.yixiang.yshop.framework.common.enums.ShopCommonEnum;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.util.object.BeanUtils;
import co.yixiang.yshop.framework.mybatis.core.query.LambdaQueryWrapperX;
import co.yixiang.yshop.module.crm.controller.admin.crmanalysis.vo.*;
import co.yixiang.yshop.module.crm.dal.dataobject.crmclues.CrmCluesDO;
import co.yixiang.yshop.module.crm.dal.dataobject.crmcontract.CrmContractDO;
import co.yixiang.yshop.module.crm.dal.dataobject.crmcontractreceivables.CrmContractReceivablesDO;
import co.yixiang.yshop.module.crm.dal.dataobject.crmcustomer.CrmCustomerDO;
import co.yixiang.yshop.module.crm.dal.dataobject.crmrecord.CrmRecordDO;
import co.yixiang.yshop.module.crm.dal.mysql.crmachievement.CrmAchievementMapper;
import co.yixiang.yshop.module.crm.dal.mysql.crmclues.CrmCluesMapper;
import co.yixiang.yshop.module.crm.dal.mysql.crmcontract.CrmContractMapper;
import co.yixiang.yshop.module.crm.dal.mysql.crmcontractreceivables.CrmContractReceivablesMapper;
import co.yixiang.yshop.module.crm.dal.mysql.crmcustomer.CrmCustomerMapper;
import co.yixiang.yshop.module.crm.dal.mysql.crmrecord.CrmRecordMapper;
import co.yixiang.yshop.module.crm.enums.CluesStatusEnum;
import co.yixiang.yshop.module.crm.enums.ContractStatusEnum;
import co.yixiang.yshop.module.crm.enums.TypesEnum;
import co.yixiang.yshop.module.system.api.user.AdminUserApi;
import co.yixiang.yshop.module.system.api.user.dto.AdminUserRespDTO;
import co.yixiang.yshop.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import co.yixiang.yshop.module.system.controller.admin.user.vo.user.UserPageReqVO;
import co.yixiang.yshop.module.system.dal.dataobject.dept.DeptDO;
import co.yixiang.yshop.module.system.dal.dataobject.dict.DictDataDO;
import co.yixiang.yshop.module.system.dal.dataobject.user.AdminUserDO;
import co.yixiang.yshop.module.system.dal.mysql.user.AdminUserMapper;
import co.yixiang.yshop.module.system.service.dept.DeptService;
import co.yixiang.yshop.module.system.service.dict.DictDataService;
import co.yixiang.yshop.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户分析 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CrmAchievementMapper achievementMapper;
    @Resource
    private DeptService deptService;
    @Resource
    private AdminUserService userService;
    @Resource
    private CrmContractMapper contractMapper;
    @Resource
    private CrmContractReceivablesMapper contractReceivablesMapper;
    @Resource
    private AdminUserMapper userMapper;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private CrmCluesMapper crmCluesMapper;
    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DictDataService dictDataService;
    @Resource
    private CrmCustomerMapper customerMapper;
    @Resource
    private CrmRecordMapper crmRecordMapper;

    @Override
    public CustomerLevelVO getCustomerLevel() {
        List<DictDataDO> list = dictDataService.getDictDataList(CommonStatusEnum.ENABLE.getStatus(), "customer_level");
        List<Long> allCustomer = new ArrayList<>();
        List<Long> dealCustomer = new ArrayList<>();

        list.forEach(v->{
            LambdaQueryWrapper<CrmCustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrmCustomerDO::getLevel,v.getValue());
            Long all = customerMapper.selectCount(wrapper);
            wrapper.eq(CrmCustomerDO::getDealStatus, ShopCommonEnum.IS_STATUS_1.getValue());
            Long deal = customerMapper.selectCount(wrapper);
            allCustomer.add(all);
            dealCustomer.add(deal);
        });
        List<String> data = list.stream().map(DictDataDO::getLabel).collect(Collectors.toList());

        return CustomerLevelVO.builder().data(data).allCustomer(allCustomer).dealCustomer(dealCustomer).build();
    }

    @Override
    public CustomerLevelVO getCustomerSource() {
        List<DictDataDO> list = dictDataService.getDictDataList(CommonStatusEnum.ENABLE.getStatus(), "customer_source");
        List<Long> allCustomer = new ArrayList<>();
        List<Long> dealCustomer = new ArrayList<>();

        list.forEach(v->{
            LambdaQueryWrapper<CrmCustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrmCustomerDO::getSource,v.getValue());
            Long all = customerMapper.selectCount(wrapper);
            wrapper.eq(CrmCustomerDO::getDealStatus, ShopCommonEnum.IS_STATUS_1.getValue());
            Long deal = customerMapper.selectCount(wrapper);
            allCustomer.add(all);
            dealCustomer.add(deal);
        });
        List<String> data = list.stream().map(DictDataDO::getLabel).collect(Collectors.toList());

        return CustomerLevelVO.builder().data(data).allCustomer(allCustomer).dealCustomer(dealCustomer).build();
    }


    @Override
    public CustomerLevelVO getCustomerIndustry() {
        List<DictDataDO> list = dictDataService.getDictDataList(CommonStatusEnum.ENABLE.getStatus(), "customer_industry");
        List<Long> allCustomer = new ArrayList<>();
        List<Long> dealCustomer = new ArrayList<>();

        list.forEach(v->{
            LambdaQueryWrapper<CrmCustomerDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CrmCustomerDO::getIndustry,v.getValue());
            Long all = customerMapper.selectCount(wrapper);
            wrapper.eq(CrmCustomerDO::getDealStatus, ShopCommonEnum.IS_STATUS_1.getValue());
            Long deal = customerMapper.selectCount(wrapper);
            allCustomer.add(all);
            dealCustomer.add(deal);
        });
        List<String> data = list.stream().map(DictDataDO::getLabel).collect(Collectors.toList());

        return CustomerLevelVO.builder().data(data).allCustomer(allCustomer).dealCustomer(dealCustomer).build();
    }

    @Override
    public PageResult<UserVolumeVO> getCustomerVolume(AchievementPageReqVO pageReqVO) {
        UserPageReqVO userPageReqVO = new UserPageReqVO();
        userPageReqVO.setPageNo(pageReqVO.getPageNo());
        userPageReqVO.setPageSize(pageReqVO.getPageSize());
        userPageReqVO.setUsername(pageReqVO.getName());
        PageResult<AdminUserDO> pageResult = userService.getUserPage(userPageReqVO);
        PageResult<UserVolumeVO> pageResult1 = BeanUtils.toBean(pageResult,UserVolumeVO.class);
        pageResult1.getList().forEach(v -> {
            LambdaQueryWrapperX<CrmCustomerDO> wrapperX = new LambdaQueryWrapperX<>();
            wrapperX.eq(CrmCustomerDO::getOwnerUserId,v.getId())
                    .betweenIfPresent(CrmCustomerDO::getCreateTime,pageReqVO.getCreateTime());
            Long customerCount = customerMapper.selectCount(wrapperX);
            wrapperX.eq(CrmCustomerDO::getDealStatus,ShopCommonEnum.IS_STATUS_1.getValue());
            Long successCount = customerMapper.selectCount(wrapperX);

            v.setCustomerCount(customerCount);
            v.setSuccessCount(successCount);

            String per = "0";
            if(customerCount > 0){
                per = NumberUtil.round(NumberUtil.div(successCount,customerCount),2)
                        .multiply(new BigDecimal("100")).toString();
            }
            v.setSuccessPer(per);

        });

        return pageResult1;
    }

    @Override
    public PageResult<UserRecordVO> getRecord(AchievementPageReqVO pageReqVO) {
        UserPageReqVO userPageReqVO = new UserPageReqVO();
        userPageReqVO.setPageNo(pageReqVO.getPageNo());
        userPageReqVO.setPageSize(pageReqVO.getPageSize());
        userPageReqVO.setUsername(pageReqVO.getName());
        PageResult<AdminUserDO> pageResult = userService.getUserPage(userPageReqVO);
        PageResult<UserRecordVO> pageResult1 = BeanUtils.toBean(pageResult,UserRecordVO.class);
        pageResult1.getList().forEach(v -> {
            LambdaQueryWrapperX<CrmRecordDO> wrapperX = new LambdaQueryWrapperX<>();
            wrapperX.eq(CrmRecordDO::getCreator,v.getId())
                    .betweenIfPresent(CrmRecordDO::getCreateTime,pageReqVO.getCreateTime());
            Long totalCount = crmRecordMapper.selectCount(wrapperX);

            wrapperX.eq(CrmRecordDO::getTypes, TypesEnum.CUSTOMER.getValue());
            Long customerCount = crmRecordMapper.selectCount(wrapperX);

            wrapperX.eq(CrmRecordDO::getTypes, TypesEnum.BUSINESS.getValue());
            Long businessCount = crmRecordMapper.selectCount(wrapperX);

            wrapperX.eq(CrmRecordDO::getTypes, TypesEnum.CLUES.getValue());
            Long cluesCount = crmRecordMapper.selectCount(wrapperX);

            v.setTotalCount(totalCount);
            v.setCustomerCount(customerCount);
            v.setBusinessCount(businessCount);
            v.setCluesCount(cluesCount);

        });

        return pageResult1;
    }
}